<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>气象风场数据渲染可视化</title>
    <script src="libwind.min.js"></script>
    <link rel="stylesheet" href="leaflet.css">
    <link rel="stylesheet" href="index.css">
    <!-- 引入闪烁marker -->
    <link rel="stylesheet" type="text/css" href="blinkmarker.css">
    <script type="text/javascript" src="blinkmarker.js"></script>
    <script src="GeometryUtil.js"></script>

</head>

<body onload="initMap()">
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            height: 100%;
        }

        #map {
            height: 100%;
        }
        .current-point {
            width: auto;
            background: white;
            position: absolute;
            top: 100px;
            left: 500px;
            z-index: 1200;
            padding: 2px 5px;
            border-radius: 5px;
        }
        .marker_timetip_3Jw {
            position:fixed;
            left: 50px;
            top: 10px;
            width: fit-content;
            box-sizing: content-box;
            z-index: 401;
            padding: 3px 10px;
            font-size: 15px;
            background: rgba(0,0,0,.38);
            color: #fff;
            border-radius: 4px;
        }
    </style>
    <div id="map"></div>
    <div id="currentPoint" class="current-point">
        <div id="wind-value"></div>
        <div id="scale-value"></div>
    </div>
    <!--<div style="position:absolute;top:120px;left: 160px;z-index: 9999;background: #3388ff">
        <input type="radio" name="baselayer" value="dz" onclick="changeBaseLayer()" >电子</input>
        <input type="radio" name="baselayer" value="yx" onclick="changeBaseLayer()"  checked >影像</input>
    </div>-->
    <!--<div id="timetip" class="marker_timetip_3Jw"><div>数据时间: 2021-07-21 19:00</div></div>-->
    <!--<input type="button" onclick="pointMarker()" value="标点" style="position:absolute;top:120px;left: 280px;z-index: 9999;"/>
    <input type="button" onclick="lineMarker()" value="标线" style="position:absolute;top:120px;left: 330px;z-index: 9999;"/>
    <input type="button" onclick="polygonMarker()" value="标面" style="position:absolute;top:120px;left: 380px;z-index: 9999;"/>
    <input type="button" onclick="formatLength()" value="测线" style="position:absolute;top:120px;left: 430px;z-index: 9999;"/>
    <input type="button" onclick="formatArea()" value="测面" style="position:absolute;top:120px;left: 480px;z-index: 9999;"/>
    <input type="button" onclick="clearMarkerLayers()" value="清除" style="position:absolute;top:120px;left: 530px;z-index: 9999;"/>
    <input type="button" onclick="changeWindDate()" value="风场" style="position:absolute;top:120px;left: 580px;z-index: 9999;"/>
    <div  style="position:absolute;top:120px;left: 630px;z-index: 9999;background: #3388ff">
        <input type="checkbox" id="wind" value="wind" onclick="clickWindLayer()">风场</input>
        <input type="checkbox" id="tp" value="tp" onclick="clickTpLayer()">降水</input>
        <input type="checkbox" id="temp" value="temp" onclick="clickTempLayer()">温度</input>
        <input type="checkbox" id="humidity" value="humidity" onclick="clickHumidityLayer()">湿度</input>
        <input type="checkbox" id="lukuang" value="lukuang" onclick="clickLukuangLayer()">路况</input>
    </div>-->
    <script>
        var map = null;
        var dzLayer = null;
        var yxLayer = null;
        function initMap(){
            //初始化地图
            dzLayer = L.tileLayer('http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', {
                minZoom: 6,
                maxZoom: 18,
                attribution: ''
            })
            // 高德
            yxLayer = L.layerGroup([L.tileLayer('http://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
                minZoom:6,
                maxZoom: 18,
                attribution: ''
            }), L.tileLayer('http://webst03.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', {
                minZoom:6,
                maxZoom: 18,
                attribution: ''
            })]);
            let baseLayers = {
                '电子': dzLayer,
                '影像': yxLayer
            };
            map = L.map('map', {
                center: [39.085294, 112.201538],
                zoom: 6,
                layers: [yxLayer], // 设置 OSM 为默认底图
                zoomControl: false
            });
            addMapListenser()
            //初始化叠加业务图层
            initLayers(baseLayers)
            //初始化标绘图层
            initMarkerLayer();
            //添加动态报警点
            addBlinkMarker();
        }
        window.addEventListener("message", function(e){
            if(e.data === 'yx'){
                if(!map.hasLayer(yxLayer)){
                    map.removeLayer(dzLayer)
                    map.addLayer(yxLayer)
                }
                return;
            }
            if(e.data ==='dz'){
                if(map.hasLayer(yxLayer)){
                    map.removeLayer(yxLayer)
                    map.addLayer(dzLayer)
                }
                return;
            }
            var dataTime = new Date();
            switch (e.data){
                case 'wind':
                    if(map.hasLayer(windLayer)) return;
                    windLayer.addTo(map)
                    break;
                case 'tp':
                    if(map.hasLayer(tpLayer)) return;
                    tpLayer.addTo(map);
                    break;
                case 'temp':
                    if(map.hasLayer(tempLayer)) return;
                    tempLayer.addTo(map);
                    break;
                case 'humidity':
                    if(map.hasLayer(humidityLayer)) return;
                    humidityLayer.addTo(map);
                    break;
                case 'lukuang':
                    if(map.hasLayer(lukuangLayer)) return;
                    lukuangLayer.addTo(map)
                    break;
                case 'point':
                    pointMarker()
                    break;
                case 'line':
                    lineMarker()
                    break;
                case 'polygon':
                    polygonMarker()
                    break;
                case 'mline':
                    formatLength()
                    break;
                case 'mpolygon':
                    formatArea()
                    break;
                case 'clear':
                    clearMarkerLayers()
                    break;
                default :
            }
           removeOverLayers(e.data)
        });
        function removeOverLayers(type) {
            if(type !== "wind" && map.hasLayer(windLayer)){
                windLayer.remove()
            }
            if(type !== "tp" && map.hasLayer(tpLayer)){
                tpLayer.remove()
            }
            if(type !== "temp" && map.hasLayer(tempLayer)){
                tempLayer.remove()
            }
            if(type !== "humidity" && map.hasLayer(humidityLayer)){
                humidityLayer.remove()
            }
            if(type !== "lukuang" && map.hasLayer(lukuangLayer)){
                lukuangLayer.remove()
            }
        }
        function changeBaseLayer() {
            var radios = document.getElementsByName('baselayer');
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) {
                    if(radios[i].value === 'yx'){
                        map.removeLayer(dzLayer)
                        map.addLayer(yxLayer)
                    }else{
                        map.removeLayer(yxLayer)
                        map.addLayer(dzLayer)
                    }
                    break;
                }
            }
        }
        function clickWindLayer() {
            var dataTime = new Date();
            if(document.getElementById('wind').checked){
                L.windUtil().getImgData(dataTime,
                    L.windUtil().options.products["wind"],
                    function (res) {
                        windLayer.setData(res)
                        windLayer.addTo(map)
                    });
            }else{
                windLayer.remove()
            }
        }
        function clickTpLayer() {
            var dataTime = new Date();
            var tpState = document.getElementById('tp').checked
            var tempState = document.getElementById('temp').checked
            if(tpState && !tempState){
                var tpproduct =  L.windUtil().options.products["tp"]
                var tpscale = chroma.scale(tpproduct.color).domain(tpproduct.range);
                L.windUtil().getImgData(
                    dataTime,
                    tpproduct,
                    function (res) {
                        var s = L.ScalarField.fromPNGGrid(res[0]);
                        tpLayer.setColor(tpscale);
                        tpLayer.setData(s, tpproduct);
                        tpLayer.addTo(map);
                    });
                document.getElementById('temp').disabled = true
            }else{
                tpLayer.remove()
                document.getElementById('temp').disabled = false
            }
        }
        function clickTempLayer() {
            var dataTime = new Date();
            var tpState = document.getElementById('tp').checked
            var tempState = document.getElementById('temp').checked
            if(!tpState && tempState){
                var tempproduct =  L.windUtil().options.products["temp"]
                var tempscale = chroma.scale(tempproduct.color).domain(tempproduct.range);
                L.windUtil().getImgData(
                    dataTime,
                    tempproduct,
                    function (res) {
                        var s = L.ScalarField.fromPNGGrid(res[0]);
                        tempLayer.setColor(tempscale);
                        tempLayer.setData(s, tempproduct);
                        tempLayer.addTo(map);
                    });
                document.getElementById('tp').disabled = true
            }else{
                tempLayer.remove()
                document.getElementById('tp').disabled = false
            }
        }
        function clickHumidityLayer() {
            var dataTime = new Date();
            var humidityState = document.getElementById('humidity').checked
            if(humidityState){
                var humidityproduct =  L.windUtil().options.products["humidity"]
                var humidityscale = chroma.scale(humidityproduct.color).domain(humidityproduct.range);
                L.windUtil().getImgData(
                    dataTime,
                    humidityproduct,
                    function (res) {
                        var s = L.ScalarField.fromPNGGrid(res[0]);
                        humidityLayer.setColor(humidityscale);
                        humidityLayer.setData(s, humidityproduct);
                        humidityLayer.addTo(map);
                    });
            }else{
                humidityLayer.remove()
            }
        }
        function clickLukuangLayer() {
            var lukuangState = document.getElementById('lukuang').checked
            if(lukuangState){
                lukuangLayer.addTo(map)
            }else{
                lukuangLayer.remove()
            }
        }
        var windLayer = null
        var tpLayer = null
        var tempLayer = null
        var humidityLayer = null
        var lukuangLayer = null
        function initLayers(baseLayers){
            var dataTime = new Date();
            //document.getElementById("timetip").innerHTML = "<div>"+"数据时间: "+L.windUtil().rebuildTime(dataTime, 9)+"</div>";
            //风场图层初始化
            windLayer = L.velocityLayer({
                // velocityScale: [0.008], //线条速度
                // particleMultiplier: 1 / 1000, //线条密度
                // maxVelocity: 10, //颜色配比
                colorScale: ["#fff"]
            });
            //风场数据加载
            L.windUtil().getImgData(dataTime,
                L.windUtil().options.products["wind"],
                function (res) {
                    windLayer.setData(res);
                    //windLayer.addTo(map);
                });

            //降水图层初始化
            tpLayer = L.scaleLayer({
                opacity: 0.7,     //透明度
                minZoom:6,
                maxZoom: 18
            });
            //降水图层数据加载
            var tpproduct =  L.windUtil().options.products["tp"]
            var tpscale = chroma.scale(tpproduct.color).domain(tpproduct.range);
            L.windUtil().getImgData(
                dataTime,
                tpproduct,
                function (res) {
                    var s = L.ScalarField.fromPNGGrid(res[0]);
                    tpLayer.setColor(tpscale);
                    tpLayer.setData(s, tpproduct);
                });
            //温度图层初始化
            tempLayer = L.scaleLayer({
                opacity: 0.7,     //透明度
                minZoom:6,
                maxZoom: 18
            });
            //温度图层数据加载
            var tempproduct =  L.windUtil().options.products["temp"]
            var tempscale = chroma.scale(tempproduct.color).domain(tempproduct.range);
            L.windUtil().getImgData(
                dataTime,
                tempproduct,
                function (res) {
                    var s = L.ScalarField.fromPNGGrid(res[0]);
                    tempLayer.setColor(tempscale);
                    tempLayer.setData(s, tempproduct);
                });
            //相对湿度图层初始化
            humidityLayer = L.scaleLayer({
                opacity: 0.7,     //透明度
                minZoom:6,
                maxZoom: 18
            });
            //相对湿度
            var humidityproduct =  L.windUtil().options.products["humidity"]
            var humidityscale = chroma.scale(humidityproduct.color).domain(humidityproduct.range);
            L.windUtil().getImgData(
                dataTime,
                humidityproduct,
                function (res) {
                    var s = L.ScalarField.fromPNGGrid(res[0]);
                    humidityLayer.setColor(humidityscale);
                    humidityLayer.setData(s, humidityproduct);
                });
            /*//相对湿度图层初始化
            humidityLayer = L.scaleLayer({
                opacity: 0.7,     //透明度
                minZoom:6,
                maxZoom: 18
            });
            //相对湿度
            var humidityproduct =  L.windUtil().options.products["humidity"]
            var humidityscale = chroma.scale(humidityproduct.color).domain(humidityproduct.range);
            L.windUtil().getImgData(
                dataTime,
                humidityproduct,
                function (res) {
                    var s = L.ScalarField.fromPNGGrid(res[0]);
                    humidityLayer.setColor(humidityscale);
                    humidityLayer.setData(s, humidityproduct);
                });*/
            var time = new Date().getDate();
            lukuangLayer = L.tileLayer('http://tm.amap.com/trafficengine/mapabc/traffictile?v=1.0&;t=1&x={x}&y={y}&z={z}&&t='+time, {
                minZoom:6,
                maxZoom: 18,
                attribution: ''
            })
            var overlays = {
                "风场": windLayer,
                "降水": tpLayer,
                "温度": tempLayer,
                "湿度": humidityLayer,
                "路况": lukuangLayer,
            };
            //L.control.layers(baseLayers, overlays,{collapsed:false, hideSingleBase:true}).addTo(map);
            L.marker([35, 120]).addTo(map);
        }
        function addMapListenser() {
            map.on("mousemove", function (e) {
                if (document.getElementById("wind-value").innerHTML == "" &&
                    document.getElementById("scale-value").innerHTML == "")
                {
                    document.getElementById("currentPoint").style.display = "none";
                } else {
                    document.getElementById("currentPoint").style.display = "block";
                }
            });
        }
        function changeWindDate(){
            /*var dataTime = new Date("2022","01",0,11,12,20)
            L.windUtil().getImgData(dataTime,
                L.windUtil().options.products["wind"],
                function (res) {
                    windLayer.setData(res);
                    windLayer.addTo(map);
                });*/
            if(map.hasLayer(lukuangLayer)) return;
            console.log(lukuangLayer)
            lukuangLayer.addTo(map)
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 初始化一些符号属性
        var markersLayer = null;
        var currentMarkerGroup = null;
        var marker_zindex = 2000
        var moveMarker = L.marker([0, 0], {
            zIndexOffset: marker_zindex
        })
        var moveIcon = L.marker([0, 0], {
            zIndexOffset: marker_zindex
        })
        var clickFunction = null;
        var dblclickFunction = null;
        var moveFunction = null;
        var rightClickFunction = null;
        function initMarkerLayer() {
            markersLayer = L.geoJSON([], {
                style: function (feature) {
                    return {
                        color: '#237CC9',
                        weight: 2,
                        fillColor: '#237CC9',
                        fillOpacity: 0.2
                    }
                }
            }).addTo(map)
            currentMarkerGroup = L.layerGroup([]).addTo(map)
        }
        // 取消标记侦听器
        function cancleMarkerListener () {
            if (clickFunction) {
                map.off('click', clickFunction)
            }
            if (dblclickFunction) {
                map.off('dblclick', dblclickFunction)
            }
            if (moveFunction) {
                map.off('mousemove', moveFunction)
            }
            if (rightClickFunction) {
                map.off('contextmenu', rightClickFunction)
            }
        }
        function clearMarkerLayers() {
            if (map.hasLayer(currentMarkerGroup)) {
                currentMarkerGroup.clearLayers()
            }
            if (map.hasLayer(markersLayer)) {
                markersLayer.clearLayers()
            }
            addMapListenser()
            clearMeasure()
        }
        // 绘制点
        function pointMarker (e) {
            cancleMarkerListener()
            clickFunction = addClickMarker
            map.on('click', clickFunction)
            moveFunction = addMoveMarker
            map.on('mousemove', moveFunction)
            rightClickFunction = cancleMarkerListener
            map.on('contextmenu', rightClickFunction)
            //e.stopPropagation()
        }
        // 绘制点符号添加到图层中
        function addClickMarker(e) {
            const clickLocation = [e.latlng.lat, e.latlng.lng]
            cancleMarkerListener()
            const pointMarker = L.marker(clickLocation).addTo(markersLayer)
            //addTip(pointMarker)
        }
        // 添加移动符号事件
        function addMoveMarker(e) {
            map.getContainer().style.cursor = 'pointer'
            moveMarker.addTo(currentMarkerGroup)
            moveMarker.setLatLng(e.latlng)
            moveMarker.setZIndexOffset(marker_zindex)
        }
        // 添加线符号
        var poly_points = [];
        var poly_line = null;
        var dashLine = [];
        function lineMarker (e) {
            cancleMarkerListener()
            poly_points = []
            poly_line = new L.Polyline([], {
                color: '#237CC9',
                // opacity:0.6,
                weight: 2
            })// 折线
            dashLine = new L.Polyline([], {
                color: '#237CC9',
                // opacity:0.6,
                dashArray: [10, 10],
                weight: 2
            })
            clickFunction = addLineLatlng
            map.on('click', clickFunction)
            dblclickFunction = addLineMarker
            map.on('dblclick', dblclickFunction)
            moveFunction = addDashLine
            map.on('mousemove', moveFunction)
            rightClickFunction = cancleMarkerListener
            map.on('contextmenu', rightClickFunction)
        }
        // 添加线绘制点
        function addLineLatlng (e) {
            poly_points.push([e.latlng.lat, e.latlng.lng])
        }
        // 添加线绘制结束点
        function addLineMarker (e) {
            cancleMarkerListener()
            map.removeLayer(dashLine)
            if (poly_points.length > 2) {
                poly_line.setLatLngs(poly_points).addTo(markersLayer)
            }
        }
        // 在绘制线鼠标移动时显示虚线效果
        function addDashLine (e) {
            map.getContainer().style.cursor = 'pointer'
            moveIcon.addTo(currentMarkerGroup)
            if (poly_points.length > 0) {
                dashLine.setLatLngs(poly_points)
                dashLine.addLatLng([e.latlng.lat, e.latlng.lng]).addTo(currentMarkerGroup)
                moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-marker-markerTooltip' style='width: 200px'></div>", className: 'leaflet-marker-noDefaultDivIcon' }))
            } else {
                moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-marker-markerTooltip' style='width: 200px'>点击开始绘制，双击结束</div>", className: 'leaflet-marker-noDefaultDivIcon' }))
            }
            moveIcon.setLatLng(e.latlng)
            moveIcon.setZIndexOffset(marker_zindex + 20)
        }
        // 为绘制区域添加绘制事件
        var poly_points = [];
        var poly_area = null;
        var poly_now = null;
        function polygonMarker (e) {
            cancleMarkerListener()
            poly_points = []// 区域点
            poly_area = new L.Polygon([], {
                color: '#237CC9',
                // opacity:0.6,
                weight: 2,
                fillColor: '#237CC9',
                fillOpacity: 0.2
            })
            poly_now = new L.Polygon([], {
                color: '#237CC9',
                // opacity:0.6,
                weight: 2,
                dashArray: [10, 10],
                fillColor: '#237CC9',
                fillOpacity: 0.3
            })
            clickFunction = addPolyLatlng
            map.on('click', clickFunction)
            dblclickFunction = addPloygonMarker
            map.on('dblclick', dblclickFunction)
            moveFunction = addPolyNow
            map.on('mousemove', moveFunction)
            rightClickFunction = cancleMarkerListener
            map.on('contextmenu', rightClickFunction)
        }
        // 添加区域绘制点
        function addPolyLatlng (e) {
            poly_points.push([e.latlng.lat, e.latlng.lng])
        }
        // 添加区域绘制结束点
        function addPloygonMarker (e) {
            cancleMarkerListener()
            map.removeLayer(poly_now)
            if (poly_points.length > 2) {
                poly_area.setLatLngs(poly_points).addTo(markersLayer)
                const tipLocation = poly_points[poly_points.length - 1]
            }
        }
        // 在绘制区域鼠标移动时显示虚线效果
        function addPolyNow (e) {
            map.getContainer().style.cursor = 'pointer'
            moveIcon.addTo(currentMarkerGroup)
            if (poly_points.length > 0) {
                poly_now.setLatLngs(poly_points)
                poly_now.addLatLng([e.latlng.lat, e.latlng.lng]).addTo(currentMarkerGroup)
                moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-marker-markerTooltip' style='width: 200px'></div>", className: 'leaflet-marker-noDefaultDivIcon' }))
            } else {
                moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-marker-markerTooltip' style='width: 200px'>点击开始绘制，双击结束</div>", className: 'leaflet-marker-noDefaultDivIcon' }))
            }
            moveIcon.setLatLng(e.latlng)
            moveIcon.setZIndexOffset(marker_zindex + 20)
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        var lengthGroup = null
        var layerThisNum = 0
        var distance = 0
        var divMeasureIcon = null
        var measure_poly_points = []
        var measure_poly_line = null
        var measure_dashLine = null
        var clickMeasureFunction = null
        var moveMeasureFunction = null
        var dblclickMeasureFunction = null
        var rightClickMeasureFunction = null
        var measure_layerGroup = []
        var measure_zindex = 2000
        var measureNum = 0
        var measure_moveIcon = L.marker([0, 0], {
            zIndexOffset: measure_zindex
        })
        var clickMarkerMeasureOptions = {
            radius: 3,
            color: 'red',
            opacity: 0.6,
            weight: 2,
            fillColor: '#FFFFFF',
            fillOpacity: 1
        }
        var _measureContainer = null
        function cancleMeasureListener () {
            let i
            if (map._markerControl && (map.hasLayer(map._markerControl.moveIcon) || map.hasLayer(map._markerControl.moveMarker))) {
                map._markerControl.cancleMarkerListener()
            }
            if (map._identifyControl) {
                const identifyControl = map._identifyControl
                for (i = 0; i < identifyControl._identifycontainer.childNodes.length; i++) {
                    if (identifyControl._identifycontainer.childNodes[i].hasAttribute('class')) {
                        identifyControl._identifycontainer.childNodes[i].removeAttribute('class')
                        identifyControl.cancleIdentifyListener()
                        break
                    }
                }
            }
            if (map._projToolsControl && $(map._projToolsControl._container).hasClass('leaflet-projTools-active')) {
                const projToolsControl = map._projToolsControl
                if ($(projToolsControl._container).hasClass('leaflet-projTools-active')) {
                    projToolsControl.cancleProjToolListener()
                }
            }
            if (_measureContainer) {
                for (i = 0; i < _measureContainer.childNodes.length; i++) {
                    _measureContainer.childNodes[i].removeAttribute('class')
                }
            }
            if (clickMeasureFunction) {
                map.off('click', clickMeasureFunction)
            }
            if (dblclickMeasureFunction) {
                map.off('dblclick', dblclickMeasureFunction)
            }
            if (moveMeasureFunction) {
                map.off('mousemove', moveMeasureFunction)
            }
            if (rightClickMeasureFunction) {
                map.off('contextmenu', rightClickMeasureFunction)
            }
            if (map.hasLayer(map._measureControl)) {
                measure_moveIcon.removeFrom(map)
            }
            map.getContainer().style.cursor = '-webkit-grab'
        }
        function clearNowMeasure () {
            if (map.hasLayer(map._measureControl)) {
                measure_layerGroup[measure_layerGroup.length - 1].clearLayers()
            }
            cancleMeasureListener()
        }
        function formatLength (e) {
            cancleMarkerListener()
            clearNowMeasure()
            map.getContainer().style.cursor = 'pointer'
            lengthGroup = L.layerGroup([]).addTo(map)
            measure_layerGroup.push(lengthGroup)
            layerThisNum = measureNum++
            measure_poly_points= []// 所有线段的点
            measure_poly_line = new L.Polyline([], {// 单击后显示的实线
                color: 'red',
                opacity: 0.6,
                weight: 2
            })
            measure_dashLine = new L.Polyline([], {// 跟随鼠标移动的虚线
                color: 'red',
                opacity: 0.6,
                dashArray: [10, 10],
                weight: 2
            })
            distance = 0
            divMeasureIcon = L.marker([0, 0], {
                zIndexOffset: measure_zindex,
                riseOnHover: true
            })
            clickMeasureFunction = addMeasureLineLatlng
            map.on('click', clickMeasureFunction)
            moveMeasureFunction = addMeasureDashLine
            map.on('mousemove', moveMeasureFunction)
            dblclickMeasureFunction = showMeasureLine
            map.on('dblclick', dblclickMeasureFunction)
            rightClickMeasureFunction = cancleFormatLength
            map.on('contextmenu', rightClickMeasureFunction)
        }
        var clickMeasureLocation = null
        var clickMeasureMarker = null
        function addMeasureLineLatlng (e) {
            measure_zindex += 10
            clickMeasureLocation = [e.latlng.lat, e.latlng.lng]
            measure_poly_points.push(clickMeasureLocation)
            measure_poly_line.addLatLng(e.latlng)
            lengthGroup.addLayer(measure_poly_line)
            clickMeasureMarker = L.circleMarker(clickMeasureLocation, clickMarkerMeasureOptions).addTo(lengthGroup)
            if (measure_poly_points.length - 1 > 0) {
                const lastLocation = measure_poly_points[measure_poly_points.length - 2]
                distance = Number(distance) + Number(e.latlng.distanceTo(new L.LatLng(lastLocation[0], lastLocation[1])) / 1000)
                if (e.latlng.lat !== lastLocation[0] && e.latlng.lng !== lastLocation[1]) {
                    divMeasureIcon = L.marker(clickMeasureLocation, {
                        zIndexOffset: measure_zindex,
                        icon: L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>" + outputLength(distance) + '</div>', className: 'leaflet-measure-noDefault' }),
                        riseOnHover: true
                    })
                    divMeasureIcon.setZIndexOffset(measure_zindex)
                    divMeasureIcon.addTo(lengthGroup)
                }
            } else {
                divMeasureIcon = L.marker(clickMeasureLocation, {
                    zIndexOffset: measure_zindex,
                    icon: L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>起点</div>", className: 'leaflet-measure-noDefault' }),
                    riseOnHover: true
                })
                divMeasureIcon.setZIndexOffset(measure_zindex)
                divMeasureIcon.addTo(lengthGroup)
            }
        }
        function addMeasureDashLine (e) {
            lengthGroup.addLayer(measure_dashLine)
            measure_moveIcon.addTo(lengthGroup)
            if (measure_poly_points.length > 0) {
                const lastLocation = [measure_poly_points[measure_poly_points.length - 1][0], measure_poly_points[measure_poly_points.length - 1][1]]
                const dashPoints = [
                    lastLocation,
                    [e.latlng.lat, e.latlng.lng]
                ]
                const nowDistance = Number(distance) + Number((e.latlng.distanceTo(new L.LatLng(lastLocation[0], lastLocation[1]))) / 1000)
                measure_dashLine.setLatLngs(dashPoints)
                measure_moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>当前" + outputLength(nowDistance) + '</div>', className: 'leaflet-measure-noDefault' }))
            } else {
                measure_moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>点击开始测量距离，双击结束</div>", className: 'leaflet-measure-noDefault' }))
            }
            measure_moveIcon.setLatLng(e.latlng)
            measure_moveIcon.setZIndexOffset(measure_zindex + 20)
        }
        function showMeasureLine (e) {
            cancleMeasureListener()
            lengthGroup.removeLayer(measure_dashLine)
            if (distance.toFixed(2) === 0) {
                lengthGroup.clearLayers()
            } else {
                lengthGroup.removeLayer(divMeasureIcon)
                const lastIcon = L.marker(clickMeasureLocation, {
                    zIndexOffset: measure_zindex,
                    riseOnHover: true,
                    icon: L.divIcon({
                        html: '<div class=\'leaflet-measure-measureTooltip\'>' + outputLength(distance) + '</div>',
                        className: 'leaflet-measure-noDefault'
                    })
                })
                lastIcon.setZIndexOffset(measure_zindex)
                lastIcon.addTo(lengthGroup)
                addDeleteBtn(lastIcon)
            }
        }
        function cancleFormatLength (e) {
            if (distance === 0) {
                clearNowMeasure()
            } else {
                cancleMeasureListener()
                lengthGroup.removeLayer(measure_dashLine)
                const lengthGroupLayers = lengthGroup.getLayers()
                addDeleteBtn(lengthGroupLayers[lengthGroupLayers.length - 1])
            }
        }
        function addDeleteBtn (lastIcon) {
            const measureLayerNum = layerThisNum
            const divIconArr = lastIcon.getPane().getElementsByClassName('leaflet-measure-noDefault')
            const deleteImg = L.DomUtil.create('img', 'leaflet-measure-deleteBtn', divIconArr[divIconArr.length - 1].childNodes[0])
            deleteImg.type = 'img'
            deleteImg.src = './images/clearGray.png'
            L.DomEvent.addListener(deleteImg, 'click', function () {
                measure_layerGroup[measureLayerNum].clearLayers()
            })
        }
        function outputLength (distance) {
            let outputLength
            if (distance < 1) {
                outputLength = Number(distance * 1000).toFixed(2) + 'm'
            } else {
                outputLength = Number(distance).toFixed(2) + 'km'
            }
            return outputLength
        }
        var areaGroup = null
        var measure_ploy_area = null
        var measure_ploy_now = null
        function formatArea (e) {
            cancleMarkerListener()
            clearNowMeasure()
            map.getContainer().style.cursor = 'pointer'
            areaGroup = L.layerGroup([]).addTo(map)
            measure_layerGroup.push(areaGroup)
            layerThisNum = measureNum++
            measure_poly_points= []// 区域点
            measure_ploy_area = new L.Polygon([], {
                color: 'red',
                opacity: 0.6,
                weight: 2,
                fillColor: 'red',
                fillOpacity: 0.1
            })

            measure_ploy_now = new L.Polygon([], {
                color: 'red',
                opacity: 0.6,
                weight: 2,
                dashArray: [10, 10],
                fillColor: 'red',
                fillOpacity: 0.3
            })

            clickMeasureFunction = addMeasurePloyLatlng
            map.on('click', clickMeasureFunction)
            moveMeasureFunction = addMeasurePolyNow
            map.on('mousemove', moveMeasureFunction)
            dblclickMeasureFunction = showMeasurePoly
            map.on('dblclick', dblclickMeasureFunction)
            rightClickMeasureFunction = cancleFormatArea
            map.on('contextmenu', rightClickMeasureFunction)
        }
        function cancleFormatArea (e) {
            if (measure_poly_points.length < 3) {
                clearNowMeasure()
            } else {
                showMeasurePoly()
            }
        }
        function addMeasurePloyLatlng (e) {
            clickMeasureLocation = [e.latlng.lat, e.latlng.lng]
            measure_poly_points.push(clickMeasureLocation)
            clickMeasureMarker = L.circleMarker(clickMeasureLocation, clickMarkerMeasureOptions).addTo(areaGroup)
        }
        function addMeasurePolyNow (e) {
            areaGroup.addLayer(measure_ploy_now)
            measure_moveIcon.addTo(areaGroup)
            if (measure_poly_points.length > 0) {
                measure_ploy_now.setLatLngs(measure_poly_points)
                measure_ploy_now.addLatLng([e.latlng.lat, e.latlng.lng])
                const nowArea = L.GeometryUtil.readableArea(L.GeometryUtil.geodesicArea(measure_ploy_now.getLatLngs()[0]), 1)
                measure_moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>当前" + nowArea + '</div>', className: 'leaflet-measure-noDefault' }))
                measure_moveIcon.setLatLng(measure_ploy_now.getCenter())
            } else {
                measure_moveIcon.setIcon(L.divIcon({ html: "<div class='leaflet-measure-measureTooltip'>点击开始测量面积，双击结束</div>", className: 'leaflet-measure-noDefault' }))
                measure_moveIcon.setLatLng(e.latlng)
            }
            measure_moveIcon.setZIndexOffset(measure_zindex + 20)
        }
        function showMeasurePoly () {
            cancleMeasureListener()
            measure_zindex += 10
            areaGroup.removeLayer(measure_ploy_now)
            measure_ploy_area.setLatLngs(measure_poly_points)
            areaGroup.addLayer(measure_ploy_area)
            for (let i = 0; i < measure_poly_points.length; i++) {
                L.circleMarker(measure_poly_points[i], {
                    radius: 3,
                    color: 'red',
                    opacity: 0.6,
                    weight: 2,
                    fillColor: '#FFFFFF',
                    fillOpacity: 1
                }).addTo(areaGroup)
            }
            const lastArea = L.GeometryUtil.readableArea(L.GeometryUtil.geodesicArea(measure_ploy_area.getLatLngs()[0]), 1)
            if (lastArea === '0.00 m&sup2') {
                areaGroup.clearLayers()
                return;
            }
            const lastIcon = L.marker(measure_ploy_area.getCenter(), {
                zIndexOffset: measure_zindex,
                riseOnHover: true,
                icon: L.divIcon({
                    html: '<div class=\'leaflet-measure-measureTooltip\'>总计' + lastArea + '</div>',
                    className: 'leaflet-measure-noDefault'
                })
            })
            lastIcon.setZIndexOffset(measure_zindex)
            lastIcon.addTo(areaGroup)
            addDeleteBtn(lastIcon)
        }
        function clearMeasure () {
            cancleMeasureListener()
            for (let i = 0; i < measure_layerGroup.length; i++) {
                measure_layerGroup[i].clearLayers()
            }
        }
        function addBlinkMarker () {
            /*L.blinkMarker([36.694, 118.587], {
                iconSize: [50, 50],
                color: 'green',
                diveColor: 'blue',
                level: '3',
                speedTime: 2,
                title: "" }).addTo(map);
            L.blinkMarker([34.694, 112.587], { iconSize: [12, 12], color: 'green',speedTime: 0.5}).addTo(map);*/
            //L.blinkMarker([35.694, 113.587], { iconSize: [18, 18], diveColor: 'aqua' }).addTo(map);
            L.blinkMarker([32.694, 116.587], { iconSize: [25, 25], level: '3', speedTime: 1 }).addTo(map);
        }
    </script>
</body>

</html>
